package com.coldlz.mmp.proxy.handlerserver;

import com.coldlz.mmp.proxy.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.List;


public class ServerProxyWsHandler extends ChannelDuplexHandler {

    private final Logger log = LoggerFactory.getLogger(ServerProxyWsHandler.class);

    private final RemoteClient remoteClient;

    public ServerProxyWsHandler(UserContext userContext) {
        this.remoteClient = RemoteClientFactory.getClient(userContext);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
        if (!(object instanceof WebSocketFrame wsFrame)) {
            throw new RuntimeException("类型转换异常");
        }
        ByteBuf copy = wsFrame.content().copy();
        System.out.println("代理的数据： " + copy.readCharSequence(copy.readableBytes(), Charset.defaultCharset()));

        if (wsFrame instanceof TextWebSocketFrame text){
//            String content = text.text();

            remoteClient.writeAndFlush(text, future -> {
                if (!future.isSuccess()) {
                    log.error("发送 WebSocketFrame 异常...", future.cause());
                }
            });
        }else {
            throw new RuntimeException("暂不支持的类型");
        }
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        super.write(ctx, msg, promise);
    }
}
